package com.yan.token.service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yanheng
 * @data 2019/12/11 10:31
 */
public class ApiRequest {

    private String originalUrl;
    private String token;
    private String appId;
    private long timestamp;

    public ApiRequest(String originalUrl, String token, String appId, long createTime){
        this.originalUrl = originalUrl;
        this.token = token;
        this.appId = appId;
        this.timestamp = createTime;
    }

    /**
     * http(s):host:port/?appid=xxx&token=yyyy&timestamp=zzz
     * @param url
     * @return
     */
    public static ApiRequest createFromFullUrl(String url){
        Map<String, String> paramMap = new HashMap<>();
        Long aLong = 0L;
        if (url != null && url.indexOf("?") > -1){
            String originalUrl = url.substring(0, url.indexOf("?"));
            String substring = url.substring(url.indexOf("?") + 1, url.length());
            ApiRequest apiRequest = praseUrlParams(originalUrl, substring);
            return apiRequest;
        }
        return new ApiRequest("", "", "", 0L);
    }

    private static ApiRequest praseUrlParams(String originalUrl, String params) {
        Long aLong = 0L;
        Map<String, String> paramMap = new HashMap<>();
        String[] split = params.split("&");
        for(String item : split) {
            String key = item.substring(0, item.indexOf("="));
            String value = item.substring(item.indexOf("=") + 1, item.length());
            paramMap.put(key, value);
        }
        if (!paramMap.containsKey("token")) {
            throw new IllegalArgumentException("url must contain token params");
        }
        if (!paramMap.containsKey("appId")) {
            throw new IllegalArgumentException("url must contain appId params");
        }
        if (!paramMap.containsKey("timestamp")) {
            throw new IllegalArgumentException("url must contain timestamp params");
        }

        aLong = Long.parseLong(paramMap.get("timestamp"));
        ApiRequest apiRequest = new ApiRequest(originalUrl, paramMap.get("token"), paramMap.get("appId"), aLong);
        return apiRequest;
    }

    public String getOriginalUrl(){
        return originalUrl;
    }

    public String getToken(){
        return token;
    }

    public String getAppId(){
        return appId;
    }

    public long getTimestamp(){
        return timestamp;
    }
}
